<template>
  <view class="container">
    <view class="search-bar">
      <!-- <u-button type="primary" size="small" shape="circle" icon="plus" v-if="checkPermi(['business:user:add'])"
        @click="handleAdd" :customStyle="{'width': '80px', 'margin': '10px'}">新增</u-button> -->
      <u-search :disabled="true" placeholder="请输入要搜索的内容" @click="show=true"></u-search>
    </view>
    <u-line dashed></u-line>
    <view class="info-item" v-for="(item,index) in dataList" :key="index">
      <view class="info-line2">
        <text class="title">
          <imagePreview :src="item.avatar"></imagePreview>
        </text>
      </view>

      <view class="info-line">
        <text class="label-name">用户ID</text>
        <text>{{item.userId}}</text>
      </view>

      <view class="info-line">
        <text class="label-name">用户名</text>
        <text>{{item.userName}}</text>
      </view>
      <view class="info-line">
        <text class="label-name">用户昵称</text>
        <text>{{item.nickName}}</text>
      </view>

      <view class="info-line">
        <text class="label-name">用户邮箱</text>
        <text>{{item.email}}</text>
      </view>

      <view class="info-line">
        <text class="label-name">手机号码</text>
        <text>{{item.phonenumber}}</text>
      </view>

      <view class="info-line">
        <text class="label-name">帐号状态</text>
        <dict-tag :options="statusOptions" :value="item.status" />
      </view>

      <view class="info-line">
        <text class="label-name">最后登录IP</text>
        <text>{{item.loginIP}}</text>
      </view>

      <view class="info-line">
        <text class="label-name">最后登录时间</text>
        <text>{{item.loginDate}}</text>
      </view>

      <view class="info-line">
        <text class="label-name">备注</text>
        <text>{{item.remark}}</text>
      </view>
      <view class="info-btn-wrap justify-end">
        <!--        <view class="tag-item">
          <u-tag text="编辑" plain shape="circle" icon="edit-pen" @click="handleEdit(item)"
            v-if="checkPermi(['business:user:edit'])"></u-tag>
        </view> -->
        <view class="tag-item" v-if="item.userId != 1">
          <u-tag text="重置密码" plain shape="circle" icon="edit-pen" @click="handleResetPwd(item)"
            v-if="checkPermi(['system:user:resetPwd'])"></u-tag>
        </view>
        <view class="tag-item" v-if="item.userId != 1">
          <u-tag text="删除" class="tag-item" plain shape="circle" type="error" icon="trash"
            v-if="checkPermi(['system:user:remove'])" @click="handleDelete(item)"></u-tag>
        </view>
      </view>
      <u-line dashed></u-line>
    </view>
    <view class="page-footer">
      <u-empty mode="list" :marginTop="140" v-if="total == 0"></u-empty>
      <uni-pagination v-else show-icon="true" :total="total" :pageSize="queryParams.pageSize"
        :current="queryParams.pageNum" @change="getData"></uni-pagination>
      <view class="text-grey padding text-center"> 共 {{ total }}条数据 </view>
    </view>

    <u-popup :show="show" mode="bottom" @close="show = false" @open="show = true">
      <view class="search-form">
        <view class="search-title">搜索</view>
        <u--form labelPosition="left" :model="queryParams" labelWidth="100px" ref="uForm">
          <u-form-item label="排序字段" prop="sort" borderBottom>
            <uni-data-select v-model="queryParams.sort" :clear="true" :localdata="sortOptions"
              format="{label}"></uni-data-select>
          </u-form-item>

          <u-form-item label="排序方式" prop="sortType" borderBottom ref="item1">
            <u-radio-group v-model="queryParams.sortType">
              <u-radio label="升序" name="asc" :customStyle="{marginRight: '20px'}"></u-radio>
              <u-radio label="倒序" name="desc"></u-radio>
            </u-radio-group>
          </u-form-item>
          <u-gap height="30"></u-gap>

          <u-form-item label="用户ID" prop="userId" borderBottom ref="item1">
            <u--input v-model="queryParams.userId" border="none" placeholder="请输入用户ID"></u--input>
          </u-form-item>

          <u-form-item label="用户名" prop="userName" borderBottom ref="item1">
            <u--input v-model="queryParams.userName" border="none" placeholder="请输入用户账号"></u--input>
          </u-form-item>

        </u--form>

        <view class="btn-group">
          <u-button text="重置" icon="reload" :customStyle="{marginRight: '10px'}" shape="circle" type="success"
            @click="resetQuery"></u-button>
          <u-button text="搜索" icon="search" shape="circle" type="primary" @click="handleQuery"></u-button>
        </view>
      </view>
    </u-popup>
    <u-back-top :scroll-top="scrollTop" :bottom="180"></u-back-top>
  </view>
</template>

<script>
  import {
    checkPermi
  } from '@/utils/permission.js'
  import {
    listUser,
    delUser,
    resetUserPwd
  }
  from '@/api/system/user.js'

  export default {
    // dicts: [
    //   "sys_user_sex",
    // ],
    data() {
      return {
        scrollTop: 0,
        dataList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sortType: 'desc',
          sort: undefined,
          userId: undefined,
          deptId: undefined,
          userName: undefined,
          nickName: undefined,
          sex: undefined,
          delFlag: undefined,
        },
        total: 0,
        show: false,
        loading: false,
        // 用户类型（00系统用户）选项列表 格式 eg:{ label: '标签', value: '0'}
        userTypeOptions: [],
        // 帐号状态（0正常 1停用）选项列表 格式 eg:{ label: '标签', value: '0'}
        statusOptions: [{
            label: '正常',
            value: '0',
            raw: {
              cssClass: 'text-success'
            }
          },
          {
            label: '停用',
            value: '1'
          }
        ],
        sortOptions: [{
            label: '用户id',
            value: 'userId'
          },
          {
            label: '登录时间',
            value: 'update_time'
          }
        ]
      }
    },
    onLoad() {
      this.getList()
    },
    methods: {
      checkPermi,
      getList() {
        uni.showLoading({
          title: 'loading...'
        });
        listUser(this.queryParams).then(res => {
          if (res.code == 200) {

            this.dataList = [...this.dataList, ...res.data.result]
            this.total = res.data.totalNum;
            // this.loading = false;
          }
        })
      },
      handleAdd() {
        this.$tab.navigateTo('./edit?opertype=1')
      },
      handleEdit(e) {
        this.$tab.navigateTo('./edit?opertype=2&userId=' + e.id)
      },
      handleDelete(row) {
        const Ids = row.userId;

        this.$modal.confirm('你确定要删除吗?').then(() => {
            return delUser(Ids);
          })
          .then(() => {
            this.handleQuery();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      },
      resetQuery() {
        this.$refs.uForm.resetFields()
      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.dataList = []
        uni.startPullDownRefresh();
        this.getList()
        this.show = false
      },
      handleResetPwd(row) {
        var pwd = this.randomPwd(6)

        uni.showModal({
          title: `是否将密码重置为${pwd}`,
          success: ((res) => {
            if (res.confirm) {
              resetUserPwd(row.userId, pwd).then((result) => {
                if (result.code == 200) {
                  uni.showModal({
                    title: '重置密码成功',
                    content: `密码已被重置为${pwd}`,
                    showCancel: false,
                    success() {
                      uni.setClipboardData({
                        data: pwd,
                        success: function() {
                          console.log('success');
                        }
                      });
                    }
                  })
                }
              })
            }
          })
        })
      },
      randomPwd(length = 8) {
        const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
        let password = '';
        for (let i = 0; i < length; i++) {
          const randomIndex = Math.floor(Math.random() * characters.length);
          password += characters[randomIndex];
        }
        return password;
      },
      getData(e) {
        this.queryParams.pageNum = e.current
        this.getList()
      },
      onPullDownRefresh() {
        uni.stopPullDownRefresh()
        this.handleQuery()
      },
      onPageScroll(e) {
        this.scrollTop = e.scrollTop;
      }
    }
  }
</script>

<style lang="scss">
  @import "@/static/scss/page.scss";

  .container {
    padding-bottom: 20px;
  }
</style>